import { getMedicalOrderDetail } from '@/services/order'
import { sendMobileCodeApi } from '@/services/user'
import type { OrderDetail } from '@/types/consult'
import type { CodeType } from '@/types/USer'
import { showToast, type FormInstance } from 'vant'
import { onMounted, onUnmounted, ref, type Ref } from 'vue'

export const useOrderDetail = (id: string) => {
  const order = ref<OrderDetail>()
  const loading = ref(false)
  onMounted(async () => {
    try {
      const res = await getMedicalOrderDetail(id)
      order.value = res.data
    } finally {
      loading.value = true
    }
  })
  return { loading, order }
}

export const useMobileCode = (
  username: Ref<string>,
  type: CodeType = 'login'
) => {
  // 发送验证码
  // 想要进行清除的话必须要先进行接收,等接收了这个值之后才可以进行清除
  let timer: number
  // 记时间,先让一开始的时间为零
  const Times = ref(0)
  const form = ref<FormInstance>()
  const sendLogin = async () => {
    if (Times.value) return
    //校验规则
    // await form.value?.validate()
    const res = await sendMobileCodeApi(username.value, type)
    console.log(res)
    showToast('发送成功')
    Times.value = 60
    if (timer) clearInterval(timer)
    timer = setInterval(() => {
      // 1s执行一次,让时间的值进行一秒减1
      Times.value--
      if (Times.value <= 0) {
        // 清除定时器
        clearInterval(timer)
      }
    }, 1000)
  }
  onUnmounted(() => {
    clearInterval(timer)
  })
  return { sendLogin, Times, form }
}
